<?php

namespace App\Http\Controllers\Admin;

use App\Models\GoodsType;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\Cloudimage;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\GoodsRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class GoodsController extends Controller
{
    protected $model;
    public function __construct(Goods $goods, Cloudimage $cloudimage)
    {
        $this->model = $goods;
        $this->cloudimage = $cloudimage;
    }
    /*
     * 商品列表
     */
    public function index(Request $request)
    {
        $user = auth('admin')->user();
        $userid = $user->id;
        if($user->type == 4){
            $userid = $user->parent_id;
        }
        $result = $this->model->filter($request->all())
            ->select('goods.*', 'goods_types.goods_name as cate_name')
            ->leftJoin('goods_types', 'goods.category_id', '=', 'goods_types.id')
            ->where('goods.state', 1)
            ->where('goods.merchant_id', $userid)
            ->orderBy('goods.created_at', 'desc')
            ->paginate(config('api.page.limit'));
        $cates = GoodsType::getcates();
        return view('admins.goods.index')->with('result',$result)->with('cates',$cates);
    }
    public function create(Request $request)
    {
        //$cloudimg = DB::table('cloudimages')->where($where)->get();
        $categs = GoodsType::getcates();
        return view('admins.goods.add')->with('categs', $categs);
    }
    public function cloud(Request $request)
    {
        //
        $where = [];
        $imagesName = $request->imagesName;
        if($imagesName){
            $where['images_name'] = ['like','%$imagesName%'];
        }
        $cloudimg = DB::table('cloudimages')->where($where)->get();
       
        return view('admins.goods.cloudcs')->with('cloudimg', $cloudimg)->with('imagesName', $imagesName);
        //return response()->json(['flag' => $cloudimg]);
    }
    public function cloudcs($id)
    {
        $cloudimg = Cloudimage::find($id);
        $categs = GoodsType::getcates();
        return view('admins.goods.cloudcs', compact('categs', 'cloudimg'));
    }
     /*
      * 添加商品
      */
    public function store(GoodsRequest $request)
    {
        $categoryId = $request->categoryId;
        $merchant = auth('admin')->user();
        $merchantId = $merchant->id;
        if($merchant->type == 4){
            $merchantId = $merchant->parent_id;
        }
        $goodsName = $request->goodsName;
        $goodsUnit = $request->goodsUnit;
        $shopPrice = $request->shopPrice;
        $domainName = is_https().$_SERVER['HTTP_HOST'];
        $goodsContent = $request->goodsContent;
        $time = date('Y-m-d H:i:s', time());
        $goodsCode = self::makeGoodsCode(); // 商品编号
        $goodsImage = $request->goodsImage;
        $data = array(
            'category_id' => $categoryId,
            'merchant_id' => $merchantId,
            'goods_name' => $goodsName,
            'goods_code' => $goodsCode,
            'domainName' => $domainName,
            'goods_image' => $goodsImage,
            'created_at' => $time,
            'updated_at' => $time
        );
        $msg = '添加成功！';
        $result = 0;
        if (!empty($data)) {
            if ($goodsContent) {
                $data['goods_content'] = $goodsContent;
            }
            if ($goodsUnit) {
                $data['goods_unit'] = $goodsUnit;     
            }
            if ($shopPrice) {
                $data['shop_price'] = $shopPrice;
            }
            $result = $this->model->insert($data);
        }
        //print_r($result);die;
        return response()->json(['flag' => $result, 'msg' => $msg]);
    }
    /*
     * 生成商品编号
     */
    protected static function makeGoodsCode()
    {
        $str = 'HRC_';
        $str .= date('YmdHis');
        $str .= mt_rand(1, 9999);
        return $str;
    }
    /*
     * 修改商品
     */
    public function edit($id)
    {
        $merchant = auth('admin')->user();
        $merchantId = $merchant->id;
        if($merchant->type == 4){
            $merchantId = $merchant->parent_id;
        }
        $result = [];
        if ($id) {
            $result = $this->model->where('merchant_id', $merchantId)->find($id);
        }
        $categs = GoodsType::getcates();
        $cloudimg = DB::table("cloudimages")->get();
        return view('admins.goods.edit', ['categs' => $categs, 'result' => $result, 'cloudimg' => $cloudimg]);
    }
    /*
     * 执行修改商品
     */
    public function update(GoodsRequest $request)
    {
        $id = $request->goodsId;
        $categoryId = $request->categoryId;
        $merchant = auth('admin')->user();
        $merchantId = $merchant->id;
        if($merchant->type == 4){
            $merchantId = $merchant->parent_id;
        }
        $goodsName = $request->goodsName;
        $goodsUnit = $request->goodsUnit;
        $goodsImage = $request->goodsImage;
        $shopPrice = $request->shopPrice;
        $goodsContent = $request->goodsContent;
        $time = date('Y-m-d H:i:s', time());

        $data = [];
        if ($categoryId) {
            $data['category_id'] = $categoryId;
        }
        if ($goodsName) {
            $data['goods_name'] = $goodsName;
        }
        if ($goodsUnit) {
            $data['goods_unit'] = $goodsUnit;
        }
        if ($goodsImage) {
            $data['goods_image'] = $goodsImage;
        }
        if ($shopPrice) {
            $data['shop_price'] = $shopPrice;
        }
        if ($goodsContent) {
            $data['goods_content'] = $goodsContent;
        }
        $result = 0;
        $msg = '修改失败，请重试！';
        if (!empty($data)) {
            $data['updated_at'] = $time;

            $result = $this->model
                ->where('id', $id)
                ->where('merchant_id', $merchantId)
                ->update($data);
            if ($result) {
                $msg = '修改成功！';
            }
        }
        return response()->json(['flag' => $result, 'msg' => $msg]);
    }
    /*
   * 商品删除（软删除）
   */
    public function destroy($id)
    {
        $merchantId = auth('admin')->user()->id;
        if ($id) {
            $result = $this->model
                ->where('id', $id)
                ->where('merchant_id', $merchantId)
                ->update(['state' => 0]);
        }
        return redirect()->route('admin.goods.index');
    }
    public function uploadImage(Request $request)
    {
        $year_mouth = date("Ym", time());
        $path = 'storage/upload/images/' . $year_mouth . '/' . date("d", time()) . '/' . auth('admin')->user()->id;
        $upload_file = $request->file('goodsImage');

        // 获取文件后缀
        $fileextension = $upload_file->getClientOriginalExtension();
        $filename = date("YmdHis", time()) . '_' . mt_rand(1, 999) . '.' . $fileextension;
        $upload_file->move($path, $filename);
        $uploadFileName = "/".$path . '/' . $filename;
        
        $upload_file->isValid();
        return response()->json(['images' => $uploadFileName]);
    }
    public function cloudimg(Request $request)
    {
        //
        $result = $this->model
            ->filter($request->all())
            ->orderBy('created_at', 'desc')
            ->paginate(config('api.page.limit'));
        return view('admins.cloudimage.add')->with('result', $result);
    }
    //审核图片
    public function toexamineedit($id)
    {
        $merchant = auth('admin')->user();
        $merchantId = $merchant->id;
        if($merchant->type == 4){
            $merchantId = $merchant->parent_id;
        }
        $result = Goods::find($id);
        return view('admins.goods.toexamineedit', compact('result'));
    }
    //审核图片修改数据
    public function toexamineupdate(Request $request)
    {
        $merchant = auth('admin')->user();
        $merchantId = $merchant->id;
        if($merchant->type == 4){
            $merchantId = $merchant->parent_id;
        }
        $result = Goods::find($request->input('id'));
        $result->merchant_id = $request->input('merchant_id', $merchantId);
        $result->states = $request->input('states');
        $result->opinion = $request->input('opinion');
        if($result->save()){
            return redirect()->route('admin.goods.index')->with('success', '编辑成功');
        }else{
            return back()->with('warning','编辑失败');
        }
    }

}
